var map = null;
var poi = null;
var geocoder = null;
//Array Penyimpan Marker GPS
var markers = [];
var labels = [];

var infoWindow = null;
//selected user id
var user_id = 0;

//Timer Object Refresh GPS
var timerGps = null;
//Timer Interval Refresh GPS
var refreshInterval = 60000;

//var routes = [];
//var buntut = [];

var paths = [];
var selectedMarker = null;
var selectedMarkerId = null;
var polygonEdit = null;

//var g = google.maps;
var marker = null;
var label = null;
var vh_id = null;
var polygons = [];
var requestHandler = null;

var gaugeShow = false;
var POIControlCreated = false;
//Playback variable OLD
var index = 0;
var playbackInterval = 1000;
var playbackHandler = null;
var totalDistance = 0;
var totalSpeed = 0;
var avgSpeed = 0;
var lines = [];

var nodeTree = null;

var reportPanel;
var btnDownload = null;
var btnPlay = null;
var btnPause = null;
var btnStop = null;
var pause = false;
var reportSummary;
var measureTool = false;
var clickCount = 0;
var polyline = null;
var polygon = null;
var clickMapHandler = null;
var maps = [];
var calculateDistance = false;
var calculateArea = false;
var bgColor = '';
var gaugeSpeed = null;
var gaugeFuel = null;
var gaugeSignalGsm = null;
var gaugeSignalGps = null;
//---------------- Playback Variable--------------------
//Selected Vehicle ID for Playback
var playback_id = 0;
//Marker penanda awal playback
var beginMarker = null;
//Marker penanda akhir playback
var endMarker = null;
//Array menyimpan icon event playback, (Parkir, Alarm)
var tracksicon = [];
//Array Menyimpan Hasil Playback
var tracks = [];
//---------------- End Playback Variable----------------
var sendCommands = [];
//Array Menyimpada Data Object GPS
var gpsList = [];
var tiles = [];

var lokalOpt = {
    getTileUrl: function(coord, zoom) {
        return "http://tiles.navigasi.net/navnet-hybrid/" + zoom + "/" + coord.x + "/" + coord.y + ".png";
    },
    tileSize: new google.maps.Size(256, 256),
    isPng: true,
    maxZoom: 18,
    minZoom: 0,
    name: "Lokal"
};
var lokalType = new google.maps.ImageMapType(lokalOpt);
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
init_map = function() {
    var mapOptions = {
        zoom: 5,
        center: new google.maps.LatLng(-0.789275, 113.921327),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControlOptions: {
            mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, 'Lokal']
        }
    };
    geocoder = new google.maps.Geocoder();
    map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
    map.mapTypes.set('Lokal', lokalType);
    console.log('init_map');
};

create_command = function(cmd) {
    var now = new Date();
    var cmd_struct = {
        session: now.format("yyyymmddhhmmss"),
        id: nodeTree.id,
        cmd: cmd,
        imei: nodeTree.imei,
        send_date: now,
        response: '',
        success: false
    };
    var gps = nodeTree.gps_brand;
    if (gps === "GT06" || gps === "GT07" || gps === "GT06N" || gps === "GT02" || gps === "GT03A" || gps === "GT07"
            || gps === "TR02" || gps === "TR06") {
        switch (cmd) {
            case "restart":
                cmd_struct.cmd = "RESET#";
                break;
            case "engineoff":
                cmd_struct.cmd = "RELAY,1#";
                break;
            case "engineon":
                cmd_struct.cmd = "RELAY,0#";
                break;
            case "position":
                cmd_struct.cmd = "URL#";
                break;
        }
    } else if (gps === "GTLT") {

    }
    return cmd_struct;
};
send_command = function(cmd) {
    //var command;
    play_sound();
    var cmd_struct = create_command(cmd);
    reqCommandHandler = $.ajax({
        crossDomain: true,
        url: "http://107.170.13.48:8844"
        ,
        data: {
            packet_type: 'send_command',
            id: cmd_struct.id,
            imei: cmd_struct.imei,
            gps_brand: cmd_struct.gps_brand,
            cmd: cmd_struct.cmd
        }
    }
    );
    reqCommandHandler.done(function(msg) {
        alert(msg);
    });

    reqCommandHandler.fail(function(jqXHR, textStatus) {
        alert("Request failed: " + textStatus);
    });


};
/*
 * change_icon_mode
 * Param 1: icon_only,icon_tile, icon_angle
 * @returns {undefined}
 */
set_text_icon_visible = function() {
    if (selectedMarkerId !== null) {
        if (labels[selectedMarkerId].getMap() !== null) {
            labels[selectedMarkerId].setMap(null);
        } else {
            labels[selectedMarkerId].setMap(map);
        }
    }
};
show_speedometer = function() {
    if (gaugeShow === true) {
        return;
    }
    var homeControlDiv = document.createElement('div');
    homeControlDiv.className = 'gauge';
    var homeControl = new HomeControl(homeControlDiv);
    homeControlDiv.index = 1;
    map.controls[google.maps.ControlPosition.RIGHT_CENTER].push(homeControlDiv);
    gaugeSpeed = jQuery("#gauge_speed").gauge({
        min: 0,
        max: 200,
        label: 'Speed/Km',
        bands: [{color: "#00ff00", from: 0, to: 50}, {color: "#ffff00", from: 51, to: 100}, {color: "#FFA500", from: 101, to: 150}, {color: "#ff0000", from: 151, to: 200}]
    })
    gaugeSpeed.gauge('setValue', 0);
    gaugeFuel = jQuery("#gauge_fuel").gauge({
        min: 0,
        max: 100,
        label: 'BBM'
                //,bands: [{color: "#00ff00", from: 0, to: 50}, {color: "#ffff00", from: 51, to: 100}, {color: "#FFA500", from: 101, to: 150}, {color: "#ff0000", from: 151, to: 200}]
    })
    gaugeFuel.gauge('setValue', 40);

    gaugeSignalGsm = jQuery("#gauge_signal_gsm").gauge({
        min: 0,
        max: 10,
        label: 'Signal GSM'
                //,bands: [{color: "#00ff00", from: 0, to: 50}, {color: "#ffff00", from: 51, to: 100}, {color: "#FFA500", from: 101, to: 150}, {color: "#ff0000", from: 151, to: 200}]
    })
    gaugeSignalGsm.gauge('setValue', 6);

    gaugeSignalGps = jQuery("#gauge_signal_gps").gauge({
        min: 0,
        max: 30,
        label: 'Satelite'
                //,bands: [{color: "#00ff00", from: 0, to: 50}, {color: "#ffff00", from: 51, to: 100}, {color: "#FFA500", from: 101, to: 150}, {color: "#ff0000", from: 151, to: 200}]
    })
    gaugeSignalGps.gauge('setValue', 16);

    gaugeShow = true;
};
/**
 * The HomeControl adds a control to the map that simply
 * returns the user to Chicago. This constructor takes
 * the control DIV as an argument.
 * @constructor
 */
function HomeControl(controlDiv) {

    // Set CSS styles for the DIV containing the control
    // Setting padding to 5 px will offset the control
    // from the edge of the map
    controlDiv.style.padding = '5px';

    // Set CSS for the control border
    var controlUI = document.createElement('div');
    controlUI.style.backgroundColor = 'transparent';
    controlUI.style.borderStyle = 'dash';
    controlUI.style.width = '150px';
    controlUI.style.height = '400px';
    controlUI.style.borderWidth = '1px';
    controlUI.style.cursor = 'pointer';
    controlUI.style.textAlign = 'center';
    controlUI.style.display = "block";
    //controlUI.title = 'Click to set the map to Home';
    controlUI.id = 'gauge_container';
    controlDiv.appendChild(controlUI);

    // Set CSS for the control interior
    var controlText = document.createElement('div');
    controlText.style.fontFamily = 'Arial,sans-serif';
    controlText.style.fontSize = '12px';
    //controlText.style.paddingLeft = '4px';
    //controlText.style.paddingRight = '4px';
    controlText.innerHTML = "<canvas id='gauge_speed' width='120' height='110'></canvas>" +
            "<canvas id='gauge_fuel' width='120' height='110'></canvas>" +
            "<canvas id='gauge_signal_gsm' width='120' height='110'></canvas>" +
            "<canvas id='gauge_signal_gps' width='120' height='110'></canvas>";
    controlUI.appendChild(controlText);
}
show_poi_control = function() {
//    if (POIControlCreated === false) {
//        var poiControlDiv = document.createElement('div');
//        //poiControlDiv.className = 'gauge';
//        var poiControl = new POIControl(poiControlDiv);
//        poiControlDiv.index = 1;
//        map.controls[google.maps.ControlPosition.TOP_CENTER].push(poiControlDiv);
//        POIControlCreated = true;
//    }
//    $("#poi_container").show();

};
save_poi2 = function() {
    alert('test');
    $.messager.progress();
    $.post('php_script/save_poi.php',
            {
                id: $("#poi_id").val(),
                poi_name: $("#poi_id").val(),
                description: $("#poi_description").val(),
                lat: $("#poi_lat").val(),
                lng: $("#poi_lng").val()
            },
    function(data) {
        console.log(data);
        var result = eval('(' + data + ')');
        if (result.errorCode > 0) {
            $.messager.show({
                title: 'Error',
                msg: result.errorMsg
            });
        } else {
            $.messager.show({
                title: 'Success',
                msg: result.successMsg
            });
        }
    });
//    $("#form_poi2").form('submit', {
//        url: 'php_script/save_poi.php',
//        onSubmit: function() {
//            return true;//$(this).form('validate');
//        },
//        success: function(result) {
//            console.log(result);
//            alert(result);
//            var result = eval('(' + result + ')');
//            if (result.errorCode > 0) {
//                $.messager.show({
//                    title: 'Error',
//                    msg: result.errorMsg
//                });
//            } else {
//                $.messager.show({
//                    title: 'Success',
//                    msg: result.successMsg
//                });
//            }
//        }
//    });
};
function POIControl(controlDiv) {

    // Set CSS styles for the DIV containing the control
    // Setting padding to 5 px will offset the control
    // from the edge of the map
    controlDiv.style.padding = '5px';

    // Set CSS for the control border
    var controlUI = document.createElement('div');
    controlUI.style.cssText =
            'border: 1px solid #b1ff3e; ' +
            'padding: 2px; background-color: white;font-size:90%;-moz-border-radius: 5px;border-radius: 5px;';
//    controlUI.style.backgroundColor = 'white';
//    controlUI.style.borderStyle = 'solid';
//    controlUI.style.width = '100%';
//    controlUI.style.height = '50px';
//    controlUI.style.borderWidth = '1px';
//    controlUI.style.cursor = 'pointer';
//    controlUI.style.textAlign = 'center';
//    controlUI.style.display = "block";
    //controlUI.title = 'Click to set the map to Home';
    controlUI.id = 'poi_container';
    controlDiv.appendChild(controlUI);

    // Set CSS for the control interiorsa
    var controlText = document.createElement('div');
    controlText.style.fontFamily = 'Arial,sans-serif';
    controlText.style.fontSize = '12px';
    controlText.innerHTML = "<div id='poi_map' name='poi_map' style='width:100%;padding:5px;'><form id='form_poi2' name='form_poi2'>" +
            "<table><input type='hidden' id='path' name='path'>" +
            "<tr><td>Nama POI</td><td></td><td>Keterangan</td><td>Lat</td><td>Lng</td><td></td></tr>" +
            "<tr><td><input type='text' id='poi_name' name='poi_name'  size='20'></td><td>:</td><td><input type='text' id='poi_description' name='poi_description' size='25'></td><td><input type='text' id='poi_lat' name='poi_lat'  size='10'></td><td><input type='text' id='poi_lng' name='poi_lng' size='10'></td><td>&nbsp;<button onClick='save_poi2();'>Save</button>&nbsp;<button value='Cancel' onClick=$('#poi_container').hide();>Cancel</button></td></tr>";
    "</table></form></div>";
    controlUI.appendChild(controlText);
}
zoom_all_gps = function() {

};
/*
 * Measure Area
 * @param {type} state
 * @returns {undefined}
 */
change_map_mode = function(mode) {
    switch (mode) {
        case 'addpoi':
            break;
        case 'addgeofence':
            break;
        case 'playback':
            if (markers) {
                for (i in markers) {
                    markers[i].setMap(null);
                }
            }

            if (labels) {
                for (i in labels) {
                    labels[i].setMap(null);
                }
            }
            if (polyline) {
                polyline.setMap(null);
            }

            if (tracksicon) {
                for (i in tracksicon) {
                    tracksicon[i].setMap(null);
                }
            }
            break;
        case 'live':
            if (markers) {
                for (i in markers) {
                    markers[i].setMap(map);
                }
            }
            if (labels) {
                for (i in labels) {
                    labels[i].setMap(map);
                }
            }
            if (polyline) {
                polyline.setMap(map);
            }
            refresh_gps(user_id);
            break;
    }
};
reset_bg_toolbar_button = function() {
    $("#btn_measure_area").css("background-color", bgColor);
    $("#btn_measure_distance").css("background-color", bgColor);
    $("#btn_zoomall").css("background-color", bgColor);
    $("#btn_zoomin").css("background-color", bgColor);
    $("#btn_zoomout").css("background-color", bgColor);
};
enable_measure_area_tool = function() {
    reset_bg_toolbar_button();
    close_measure_tool();
    if (calculateArea === true) {
        calculateArea = false;
        close_measure_tool();
        return;
    }
    //Clear existing previous tool
    polygon = new google.maps.Polygon({
        map: map,
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#FF0000',
        fillOpacity: 0.35,
        draggable: true,
        editable: true,
        geodesic: true
    });
    clickMapHandler = google.maps.event.addListener(map, 'click', addLocation2);
    $("#text_measure").show();
    $("#btn_measure_area").css("background-color", '#ff0000');
    calculateArea = true;
};
/*
 * Measure Distance
 * @param {type} event
 * @returns {undefined}
 */

enable_measure_line_tool = function() {
    reset_bg_toolbar_button();
    close_measure_tool();
    if (calculateDistance === true) {
        calculateDistance = false;
        return;
    }
    //Clear existing previous tool
    close_measure_tool();
    var polyOptions = {
        strokeColor: '#FF0000',
        strokeOpacity: 1.0,
        strokeWeight: 3
    };
    polyline = new google.maps.Polyline(polyOptions);
    polyline.setMap(map);
    clickMapHandler = google.maps.event.addListener(map, 'click', addLocation);
    $("#btn_measure_distance").css("background-color", '#ff0000');
    $("#text_measure").show();
    calculateDistance = true;
};
close_measure_tool = function() {
    if (polyline !== null) {
        clearPaths();
        polyline.setMap(null);
    }
    if (polygon !== null) {
        polygon.setMap(null);
    }
    if (clickMapHandler !== null) {
        google.maps.event.removeListener(clickMapHandler);
    }
    $("#text_measure").hide();
};
function addLocation(event) {
    var path = polyline.getPath();
    path.push(event.latLng);
    var distance = google.maps.geometry.spherical.computeLength(path.getArray()) / 1000;
    //google.maps.geometry.spherical.computeArea(path.getArray())
    document.getElementById('text_measure').value = "Jarak " + distance.toFixed(2) + " Km";
}
function addLocation2(event) {
    var path = polygon.getPath();
    path.push(event.latLng);
    var distance = google.maps.geometry.spherical.computeArea(path.getArray()) / 1000;
    document.getElementById('text_measure').value = "Luas " + distance.toFixed(2) + " Km2";
}
function clearPaths() {
    var path = polyline.getPath();
    while (path.getLength()) {
        path.pop();
    }
}
set_timer = function(timer) {
    refreshInterval = timer.value;
    load_vehicle_data();
};
stop_timer = function() {
    if (requestHandler)
        requestHandler.abort();
    clearTimeout(timerGps);
};
create_iw_content = function(data) {
    var content = "<div class='iw' style='min-width:380px;min-height:170px;'>" +
            "<div class='iwh'><h3>" + data.nopol + "</h3></div>" +
            "<table>" +
            // "<tr><td style='width:90px;'>Phone</td><td>:</td><td>" + data.phone + "</td></tr>" +
            "<tr><td style='width:90px;'>Imei</td><td>:</td><td>" + data.imei + "</td></tr>" +
            "<tr><td style='width:90px;'>Status</td><td>:</td><td>" + data.status + "</td></tr>" +
            "<tr><td style='width:90px;'>ACC Status</td><td>:</td><td>" + data.acc_state + "</td></tr>" +
            "<tr><td style='width:90px;'>Tanggal</td><td>:</td><td>" + data.tdate + "</td></tr>" +
            "<tr><td>Tanggal</td><td>:</td><td>" + data.lat + "," + data.lng + "</td></tr>" +
            "<tr><td>Lokasi</td><td>:</td><td><div id='iw_content'>" + data.address + "</div></td></tr>" +
            "<tr><td>Imei</td><td>:</td><td>" + data.imei + "</td></tr>" +
            "<tr><td>Kecepatan</td><td>:</td><td>" + data.speed + " Km/Jam, Arah " + data.angle + "&deg; (" + dName(data.angle) + ")</td></tr>" +
            "</table></div>";
//            "<div class='iw_bottom' style='border-top:1px solid #000000;white-space: nowrap;'>" +
//            "<a href='#' onClick='zoomTo();'>Zoom</a>&nbsp;|&nbsp;" +
//            "<a href='#'>Get Last Position</a>&nbsp;|&nbsp;" +
//            "<a href='#' onClick='track_gps(" + data.id + ");'>Ikuti</a>&nbsp;|&nbsp;" +
//            "<a href='#' onClick='zoomTo();'>Stop Engine</a>&nbsp;|&nbsp;" +
//            "<a href='#' onClick='zoomTo();'>Start Engine</a>&nbsp;|&nbsp;</div>" +
//            "<div class='iw_bottom'>" +
//            "History Perjalanan (<a href='#' onClick='zoomTo();'>15 Menit Lalu</a>&nbsp;|&nbsp;" +
//            "<a href='#' onClick='zoomTo();'>30 Menit Lalu</a>&nbsp;|&nbsp;" +
//            "<a href='#' onClick='track_gps(" + data.id + ");'>1 Jam Lalu</a> " +
//            "<a href='#' onClick='track_gps(" + data.id + ");'>2 Jam Lalu</a> " +
//            "<a href='#' onClick='track_gps(" + data.id + ");'>3 Jam Lalu</a> " +
//            ")</div>" +
//            "</div>";
    return content;
};
update_list_gps = function(data) {
    var gpsObject = {
        id: data.id,
        nopol: data.nopol,
        tdate: data.tdate,
        imei: data.imei,
        lat: data.lat,
        lng: data.lng,
        speed: parseFloat(data.speed),
        angle: parseFloat(data.angle),
        poi: data.poi,
        address: data.address,
        needGeocoding: true
    };

    var prevObject = gpsList[data.id];
    if (prevObject !== null) {
        //Check Current Speed or Distance, if Move, set ObjectMove=true, when icon click will getocoding
        //var dist = distance(prevObject.lat, prevObject.lng, gpsObject.lat, gpsObject.lng);
        if (gpsObject.speed === 0) {
            // gpsObject.needGeocoding = false;
        }
    }
    gpsList[data.id] = gpsObject;
};
update_gps_address = function(id, address) {
    var gpsObject = gpsList[id];
    if (gpsObject !== null) {
        gpsObject.address = address;
        gpsObject.needGeocoding = false;
    }
};
//Resolve coordinate to Address
get_geocoder = function(id, lat, lng) {
    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
        var address = "";
        if (status === google.maps.GeocoderStatus.OK) {
            if (results[1]) {
                address = results[1].formatted_address;
                update_gps_address(id, address);
            } else {
                address = 'No results found';
            }
        } else {
            address = 'Geocoder failed due to: ' + status;
        }
        console.log("Geocoding Address:" + address);
        $("#iw_content").text(address);
    });

};
//Get Info Window
get_infoWindow = function(id) {
    // alert(id);
    var gObject = gpsList[id];
    if (gObject === null || gObject === 'undefine') {
        console.log("gObject === null || gObject === 'undefine'");
        return "<h1>Maaf Informasi GPS Tidak Bisa Ditampilkan</h1>";
    }
    if (gObject.needGeocoding === true) {
        console.log("gObject.needGeocoding === true");
        get_geocoder(id, gObject.lat, gObject.lng);
    } else {
        console.log("gObject.needGeocoding === false");
    }
    return create_iw_content(gObject);
};
refresh_gps = function() {
    if (timerGps !== null)
        clearTimeout(timerGps);
    if (requestHandler !== null)
        requestHandler.abort();
    clear_marker();
    requestHandler = $.getJSON('php_script/tree_vehicle.php?', {user_id: user_id}, function(objects) {
        var online = [];
        var offline = [];
        $.each(objects, function() {
            $.each(this.children, function(i, data) {
                //  console.log(v.iconCls);
                var milisecond = Math.abs(new Date() - new Date(data.tdate));
                if (milisecond >= 1000) {
                    milisecond = milisecond / 1000; //now in second
                    milisecond = Math.floor(milisecond / 60); //now Minute
                    if (milisecond <= 5) {
                        data.iconCls = 'icon-green';
                        online.push(data);
                    } else if (milisecond <= 300) {
                        data.iconCls = 'icon-yellow';
                        online.push(data);
                    } else {
                        data.iconCls = 'icon-red';
                        offline.push(data);
                    }
                } else {
                    offline.push(data);
                }
                update_list_gps(data);
                var marker = create_marker(data.id, data.lat, data.lng, 'mobil', data.speed, data.angle);
                var lbl = map_label(data.id, data.nopol, marker);
                //labels.push(lbl);
                labels[data.id] = lbl;
                markers[data.id] = marker;
            });
        });
        //Inside function.js
        refresh_tree(objects, online, offline);
    });
    timerGps = setTimeout("refresh_gps();", refreshInterval);
};
map_label = function(id, nopol, marker)
{
    var label = new Label({
        id: id,
        map: map
    });
    label.bindTo('position', marker, 'position');
    label.set('text', nopol);

//    console.log(labels[id]);
//    if( (labels[id]!==null) || (labels[id] !=='undefined')){
//        label.setMap(labels[id].getMap());
//    }
    return label;
};
dName = function(a) {
    if ((a >= 337.5) && (a >= 0) && (a <= 22))
        return "Utara";
    if ((a >= 22.5) && (a <= 67))
        return "Timur Laut";
    if ((a >= 67.5) && (a <= 112))
        return "Timur";
    if ((a >= 112.5) && (a <= 157))
        return "Tenggara";
    if ((a >= 157.5) && (a <= 202))
        return "Selatan";
    if ((a >= 202.5) && (a <= 247))
        return "Barat Daya";
    if ((a >= 247.5) && (a <= 292))
        return "Barat";
    if ((a >= 292.5) && (a <= 337))
        return "Barat Laut";
};
load_vehicle_data = function(showbound)
{
    if (timerGps !== null)
        clearTimeout(timerGps);
    if (requestHandler !== null)
        requestHandler.abort();
    var bounds = new google.maps.LatLngBounds();
    clear_marker();
    requestHandler = $.ajax({
        type: 'POST',
        url: 'php/get_vehicle.php?mode=monitor',
        dataType: 'json',
        success: function(data) {
            //console.log(data);
            $.each(data, function(i, item) {
                var iw_content = "";
                var iw_content2 = "";
                var iw_content3 = "";

                if (item.icon !== 'orang') {
                    iw_content = "<div class='iw'>" +
                            "<div class='iwh'><h3>" + item.nopol + "</h3></div>" +
                            "<table>" +
                            "<tr><td style='width:80px;'>Tanggal</td><td>:</td><td>" + item.tdate + "</td></tr>" +
                            "<tr><td>Lokasi</td><td>:</td><td>" + item.address + "</td></tr>" +
                            "<tr><td>Imei</td><td>:</td><td>" + item.imei + "</td></tr>" +
                            "<tr><td>Parkir</td><td>:</td><td>" + item.park_state + "</td></tr>" +
                            "<tr><td>Kecepatan</td><td>:</td><td>" + item.speed + " Km/Jam, Arah " + item.angle + "&deg; (" + dName(item.angle) + ")</td></tr>" +
                            "<tr><td>Jarak Tempuh</td><td>:</td><td>" + formatNumber(item.odometer) + " Km</td></tr>" +
                            "<tr><td>Mesin</td><td>:</td><td>" + eState(item.acc_state) + "</td></tr>" +
                            "<tr><td>Battery</td><td>:</td><td>" + item.batt_level + "</td></tr>" +
                            "<tr><td>Signal GPS/GSM</td><td>:</td><td>" + item.gps_signal + "/" + item.gsm_signal + "</td></tr>" +
                            "</table>" +
                            "<div class='iw_bottom'>\n\
                         <a href='#' onClick='zoomTo();'>Zoom</a>&nbsp;|&nbsp;\n\
                         <a href='tracking.php?vh_id=" + item.id + "' target='_blank'>Tracking</a>&nbsp;|&nbsp;\n\
                         <a href='#' onClick='zoomTo();'>Playback</a>&nbsp;|&nbsp;\n\
                         <a href='#' onClick='zoomTo();'>Trip Report</a>&nbsp;|&nbsp;\n\
                         <a href='#' onClick='zoomTo();'>Statistic</a>&nbsp;|&nbsp;\n\
                         <a href='control.php?vh_id=" + item.id + "' target='_blank'>Send Command</a>&nbsp;|&nbsp;\n\
                         <a href='geofence.php?vh_id=" + item.id + "' target='_blank'>Set Geofence</a>&nbsp;|&nbsp;\n\
                         <a href='#'>Fire Alarm</a></div>" +
                            "</div>";
                } else {
                    iw_content = "<div class='iw'>" +
                            "<div class='iwh'><h3>" + item.nopol + "</h3></div>" +
                            "<table>" +
                            "<tr><td style='width:80px;'>Tanggal</td><td>:</td><td>" + item.tdate + "</td></tr>" +
                            "<tr><td>Lokasi</td><td>:</td><td>" + item.address + "</td></tr>" +
                            "<tr><td>Imei</td><td>:</td><td>" + item.imei + "</td></tr>" +
                            "<tr><td>Berhenti</td><td>:</td><td>" + item.park_state + "</td></tr>" +
                            "<tr><td>Kecepatan</td><td>:</td><td>" + item.speed + " Km/Jam, Arah " + item.angle + "&deg; (" + dName(item.angle) + ")</td></tr>" +
                            "<tr><td>Jarak Tempuh</td><td>:</td><td>" + formatNumber(item.odometer) + " Km</td></tr>" +
                            "<tr><td>Akurasi</td><td>:</td><td>" + item.accuration + "</td></tr>" +
                            "</table>" +
                            "<div class='iw_bottom'>\n\
                         <a href='#' onClick='zoomTo();'>Zoom</a>&nbsp;|&nbsp;\n\
                         <a href='tracking.php?vh_id=" + item.id + "' target='_blank'>Tracking</a>&nbsp;|&nbsp;\n\
                         <a href='#' onClick='zoomTo();'>Playback</a>&nbsp;|&nbsp;\n\
                         <a href='#' onClick='zoomTo();'>Trip Report</a>&nbsp;|&nbsp;\n\
                         <a href='#' onClick='zoomTo();'>Statistic</a>&nbsp;|&nbsp;\n\
                         <a href='control.php?vh_id=" + item.id + "' target='_blank'>Send Command</a>&nbsp;|&nbsp;\n\
                         <a href='geofence.php?vh_id=" + item.id + "' target='_blank'>Set Geofence</a>&nbsp;|&nbsp;\n\
                         <a href='#'>Fire Alarm</a></div>" +
                            "</div>";
                }
                // icon = 'default';
                if ((item.icon === 'undefine') || (item.icon === '')) {
                    item.icon = 'default';
                }
                var marker = create_marker(item.id, iw_content, item.lat, item.lng, item.icon, item.speed, item.angle);
                if (marker !== null)
                    markers.push(marker);

                var label = new Label({map: map, id: item.id});
                labels.push(label);
                label.bindTo('position', marker, 'position');
                label.set('text', item.nopol);

                if (selectedMarkerId === item.id)
                    google.maps.event.trigger(marker, 'click');
                if (showbound)
                    bounds.extend(marker.getPosition());
            });
            if (showbound)
                map.fitBounds(bounds);
            bounds = null;
        }
    });
    timerGps = setTimeout("load_vehicle_data(false);", refreshInterval);
};
create_mrk = function() {
    console.log('Start Mark');
    var marker = new google.maps.Marker({
        position: map.getCenter(),
        map: map,
        title: 'Object Tracker',
        icon: 'images/playback/play.png'
    });
    map.setZoom(15);
    console.log('Stop Mark');
};
//Playback History with animation
download_history = function(vh_id, fdate, udate)
{
    stop_timer();
    if (playbackHandler !== null)
        clearTimeout(playbackHandler);
    if (requestHandler !== null)
        requestHandler.abort();

    clear_marker();
    requestHandler = $.ajax({
        url: 'php/trip_playback.php',
        beforeSend: function() {
            reportSummary.html("<div><img src='images/animation.gif'/></div>");
        },
        dataType: 'json',
        data: {vh_id: vh_id, fdate: fdate, udate: udate},
        success: function(result)
        {
            //console.log("hasil"+ result);
            $.each(result.data, function(i, item) {
                var tDetail = {
                    tdate: item.tdate,
                    lat: item.lat,
                    lng: item.lng,
                    speed: item.speed,
                    angle: item.angle,
                    address: item.address
                };
                tracks.push(tDetail);
            });
            reportSummary.html("");

            console.log("markers.length:" + tracks.length);

            if (tracks.length > 0)
            {
                index = 0;
                var myLatLng = new google.maps.LatLng(tracks[0].lat, tracks[0].lng);
                marker = new google.maps.Marker({
                    position: myLatLng,
                    map: map,
                    title: 'Here it is',
                    icon: 'images/playback/play.png'
                });
                map.setCenter(myLatLng);
                map.setZoom(15);
                btnPlay.show();
            }

            return;
        }
    });
};

download_history2 = function(vh_id, from, to)
{
    clear_tracks();
    stop_timer();
    if (requestHandler !== null) {
        requestHandler.abort();
    }
    requestHandler = $.getJSON('php_script/json_trip_report.php?', {vh_id: vh_id, from: from, until: to},
    function(objects) {
        //Create Polyline
        var tmpTracks = [];
        var numStop = 0;
        var no = 0;
        console.log("Total Data:" + objects.length);
        $.each(objects, function(i, data) {
//            if (no == 0) {
//                console.log(data);
//            }
            var currTrack = {
                tdate: data.tdate,
                tdate2: data.tdate,
                lat: data.lat,
                lng: data.lng,
                park: '',
                speed: data.speed,
                angle: data.angle,
                poi: data.poi,
                address: data.address
            };
            if (no > 0) {
                var prevTrack = tracks[no - 1];

                //Masih Parkir
                if ((prevTrack.speed <= 3) && (currTrack.speed <= 3)) {
                    tmpTracks[numStop++] = currTrack;
                    prevTrack.tdate2 = currTrack.tdate;
                    // Masih Jalan
                } else if ((prevTrack.speed > 3) && (currTrack.speed > 3)) {
                    numStop = 0;
                    tracks[no++] = currTrack;
                    //Mulai Jalan Setelah Parkir
                } else if ((prevTrack.speed <= 3) && (currTrack.speed > 3)) {
                    if (numStop > 5) {
                        prevTrack.park = diff_datetime_to_hra(prevTrack.tdate2, prevTrack.tdate);
                        tmpTracks.length = 0;
                        tmpTrack = [];
                        numStop = 0;
                    } else {
                        for (var j = 0; j < tmpTracks.length; j++) {
                            tracks[no++] = tmpTracks[j];
                        }
                        tmpTracks = [];
                        numStop = 0;
                    }
                    //Mulai Parkir Setelah Jalan
                } else if ((prevTrack.speed > 3) && (currTrack.speed <= 3)) {
                    numStop = 0;
                    tmpTracks[numStop++] = currTrack;
                } else {
                    console.log('Lost filter: Prev/Curr Speed ' + prevTrack.speed + '/' + currTrack.speed);
                }
            } else {
                tracks[no++] = currTrack;
            }

        });

        //Finally Show Data
        if (tracks.length > 0)
        {
            var polyOptions = {
                strokeColor: '#FF0000',
                strokeOpacity: 1.0,
                strokeWeight: 3
            };
            polyline = new google.maps.Polyline(polyOptions);
            polyline.setMap(map);

            var beginTrack = tracks[0];
            var endTrack = tracks[tracks.length - 1];
            var beginLatlng = new google.maps.LatLng(parseFloat(beginTrack.lat), parseFloat(beginTrack.lng));
            var endLatlng = new google.maps.LatLng(parseFloat(endTrack.lat), parseFloat(endTrack.lng));

            beginMarker = new google.maps.Marker({
                title: 'begin',
                position: beginLatlng,
                map: map,
                icon: 'themes/icons/begin.png'
            });

            endMarker = new google.maps.Marker({
                title: 'End',
                position: endLatlng,
                map: map,
                icon: 'themes/icons/end.png'
            });

            //show alarm,parking marker position
            for (var i = 0; i < tracks.length; i++) {
                if (tracks[i].alarm !== '') {
                    var marker = create_marker_playback(i, tracks[i].lat, tracks[i].lng, 'alarm.png');
                    tracksicon.push(marker);
                } else if (tracks[i].park !== '') {
                    var marker = create_marker_playback(i, tracks[i].lat, tracks[i].lng, 'stop.png');
                    tracksicon.push(marker);
                }
                var latlng = new google.maps.LatLng(parseFloat(tracks[i].lat), parseFloat(tracks[i].lng));
                var path = polyline.getPath();
                path.push(latlng);
            }
            //finally calculate distance
            var distance = google.maps.geometry.spherical.computeLength(polyline.getPath().getArray()) / 1000;
            $("#pb_distance").html(distance.toFixed(2) + " Km");
        }
        $.messager.progress('close');
    });

};
create_marker_playback = function(id, lat, lng, icon) {

    var image = new google.maps.MarkerImage('themes/icons/' + icon, new google.maps.Size(12, 12), new google.maps.Point(0, 0), new google.maps.Point(6, 6));
    var myLatLng = new google.maps.LatLng(lat, lng);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        icon: image
    });

    google.maps.event.addListener(marker, 'click', function() {
        if (infoWindow !== null)
            infoWindow.close();
        var track = tracks[id];
        var content = "<div>Event:" + track.alarm + "</br>";
        content += "Speed:" + track.speed + "</br>";
        content += "Lat:" + track.lat + "</br>";
        content += "Lng:" + track.lng + "</br>";
        content += "Stop:" + track.park + "</br>";
        content += "Poi:" + track.poi + "</br>";
        content += "Address:" + track.address + "</div>";
        infoWindow = new google.maps.InfoWindow({
            content: content
        });
        infoWindow.open(map, marker);
    });
    return marker;
};
playback = function(state) {
    switch (state) {
        case 'play':
            if (pause === false)
                index = 0;
            polyline_init();
            btnPause.show();
            btnStop.show();
            btnPlay.hide();
            play();
            break;
        case 'pause':
            pause = true;
            btnPause.hide();
            btnStop.hide();
            btnPlay.show();
            clearTimeout(playbackHandler);
            break;
        case 'stop':
            clearTimeout(playbackHandler);
            btnPause.hide();
            btnStop.hide();
            btnPlay.show();
            pause = false;
            index = 0;
            break;
    }
};
play = function() {

    console.log(playbackHandler);

    if (playbackHandler !== '')
        clearTimeout(playbackHandler);
    var latLngCurrent = new google.maps.LatLng(tracks[index].lat, tracks[index].lng);
    if (index >= 1) {
        var latLngPrev = new google.maps.LatLng(tracks[index - 1].lat, tracks[index - 1].lng);
        totalDistance = totalDistance + (google.maps.geometry.spherical.computeDistanceBetween(latLngCurrent, latLngPrev) / 1000);
    }
    polyline_addpoint(latLngCurrent);


    totalSpeed = totalSpeed + tracks[index].speed;
    if (index > 0)
        avgSpeed = totalSpeed / (index + 1);
    var tbl = "<table class='tblrpt'>";
    tbl = tbl + "<tr><td>Jarak Tempuh</td><td>:</td><td>" + totalDistance.toFixed(1) + " Km</td></tr>";
    tbl = tbl + "<tr><td>Kecepatan </td><td>:</td><td>" + tracks[index].speed + " Km/Jam</td></tr>";
    tbl = tbl + "<tr><td>Kecepatan Rata-Rata</td><td>:</td><td>" + avgSpeed + " Km</td></tr>";
    tbl = tbl + "<tr><td>Lokasi</td><td>:</td><td>" + tracks[index].address + "</td></tr>";
//    tbl = tbl + "<tr><td>Total Engine On</td><td>:</td><td>N/A</td></tr>";
//    tbl = tbl + "<tr><td>Total Engine Off</td><td>:</td><td>N/A</td></tr>";
//    tbl = tbl + "<tr><td>Total Parking</td><td>:</td><td>N/A</td></tr>";
//    tbl = tbl + "<tr><td>Total Running</td><td>:</td><td>N/A</td></tr>";
    tbl = tbl + "</table>";
    reportPanel.html(tbl);
    if (infoWindow !== null)
    {
        var html = "<div class='iw'>" +
                "Date:" + tracks[index].tdate + "<br/>" +
                "Lat/Lng:" + tracks[index].lat + "/" + tracks[index].lng + "<br/>" +
                "Speed:" + tracks[index].speed + "<br/>" +
                "Address:" + tracks[index].address + "<br/></div>";
        infoWindow.setContent(html);
    }

    if (marker !== null) {
        console.log('marker not null');
        map.setCenter(latLngCurrent);
        marker.setPosition(latLngCurrent);
    } else {
        console.log('marker=null');
    }
    playbackHandler = setTimeout("play();", playbackInterval);
    index++;
    if (index >= tracks.length) {
        playback('stop');
    }
};
polyline_init = function()
{
    polyline = new google.maps.Polyline({
        path: paths,
        strokeColor: "#80ff00",
        strokeOpacity: 0.8,
        strokeWeight: 3
    });
    polyline.setMap(map);
};
polyline_addpoint = function(latlng) {
    var path = polyline.getPath();
    path.push(latlng);
};
polyline_clear = function(latlng) {
    var path = polyline.getPath();
    path.clear();
    polyline.setMap(null);
};
zoomTo = function(latlng) {
    if (latlng !== null)
    {
        console.log('selected_gps !=null');
        map.setCenter(latlng);
        map.setZoom(map.getZoom() + 2);
    }
    return;
};
zoomAll = function() {
    if (markers) {
        var bounds = new google.maps.LatLngBounds();
        for (i in markers) {
            bounds.extend(markers[i].getPosition());
        }
        map.fitBounds(bounds);
    }
};
select_gps = function(id) {
    var gpsObject = gpsList[id];

    if (gpsObject !== null) {
        gaugeSpeed = jQuery("#gauge_speed").gauge({
            min: 0,
            max: 200,
            label: gpsObject.nopol,
            bands: [{color: "#00ff00", from: 0, to: 50}, {color: "#ffff00", from: 51, to: 100}, {color: "#FFA500", from: 101, to: 150}, {color: "#ff0000", from: 151, to: 200}]
        })
        gaugeSpeed.gauge('setValue', gpsObject.speed);
    }
    selectedMarker = markers[id];
    if (selectedMarker !== null) {
        selectedMarkerId = id;
        zoomTo(selectedMarker.getPosition());
        google.maps.event.trigger(selectedMarker, 'click');
    }
};
create_marker = function(id, lat, lng, icon_type, speed, angle) {
    var myLatLng = new google.maps.LatLng(lat, lng);
    var marker = new google.maps.Marker({
        title: id,
        position: myLatLng,
        map: map,
        icon: 'images/gps/' + create_icon(icon_type, speed, angle)
    });

    google.maps.event.addListener(marker, 'click', function() {
        selectedMarker = marker;
        selectedMarkerId = id;
        if (infoWindow !== null)
            infoWindow.close();
        infoWindow = new google.maps.InfoWindow({
            content: get_infoWindow(id)
        });
        infoWindow.open(map, marker);
    });
    return marker;
};
clear_marker = function() {
    if (markers) {
        for (i in markers) {
            markers[i].setMap(null);
        }
        markers.length = 0;
    }

    if (labels) {
        for (i in labels) {
            labels[i].setMap(null);
        }
        labels.length = 0;
    }

    if (polyline) {
        polyline_clear();
    }
};

clear_tracks = function() {
    if (tracksicon) {
        for (i in tracksicon) {
            tracksicon[i].setMap(null);
        }
        tracksicon.length = 0;
    }
    if (polyline) {
        polyline_clear();
    }
    tracks = [];
};
create_icon = function(icon, s, a)
{
    var state = 'run.gif';
    if (s <= 0)
        state = 'stop.gif';
    switch (icon) {
        case 'orang':
            return icon + "/orang.png";
            break;

        default:
            if ((a >= 337.5) || ((a >= 0) && (a <= 22)))
                return icon + "/0-" + state;
            if ((a >= 22.5) && (a <= 67))
                return icon + "/45-" + state;
            if ((a >= 67.5) && (a <= 112))
                return icon + "/90-" + state;
            if ((a >= 112.5) && (a <= 157))
                return icon + "/135-" + state;
            if ((a >= 157.5) && (a <= 202))
                return icon + "/180-" + state;
            if ((a >= 202.5) && (a <= 247))
                return icon + "/225-" + state;
            if ((a >= 247.5) && (a <= 292))
                return icon + "/270-" + state;
            if ((a >= 292.5) && (a <= 337))
                return icon + "/315-" + state;
            else
                return "default/icon.gif";
            break;
    }
};
/*******************************************/
/*          POLYGON /GEOFENCE              */
/*******************************************/
//parse geofence from selected datarow
edit_geofence_datagrid = function() {
    var row = gridGeofence.datagrid('getSelected');
    if (row !== null) {
        draw_geofence(row.id, row.vh_id, row.name, row.geofence);
        edit_geofence(row.id);
    }
};
load_geofence = function(vh_id) {
    console.log("Load Geofence,vh_id:" + vh_id);
    clear_geofence();
    if (requestHandler !== null) {
        requestHandler.abort();
    }
    requestHandler = $.getJSON('php_script/get_geofence.php', {vh_id: vh_id}, function(data) {
        console.log(data);
        var html = "";
        var no = 1;
        html = "<table class='tblgeofence'><tr><td class='w100'>Nama</td><td class='w100'>Operate</td></tr>";
        $.each(data, function(i, item) {
            console.log(item);
            draw_geofence(item.id, item.vh_id, item.name, item.geofence);
            html = html + "<tr><td>" + item.name + "</td><td><a href='#' onClick='show_poi_control();'>POI</a><a href='#' onClick='del_geofence(" + item.id + ");'>Del</a>&nbsp;|&nbsp;<a href='#' onClick='edit_geofence(" + item.id + ");'>Edit</a></td></tr>";
            //html = html + "<tr id='row_"+ no +"'><td><input type='text></td><td><a href='#' onClick='del_geofence(" + item.id + ");'>Del</a>&nbsp;|&nbsp;<a href='#' onClick='edit_geofence(" + item.id + ");'>Edit</a></td></tr>";
            no++;
        });
        html = html + "</table>";
        $("#table_geofence").html(html);
    });
};
draw_geofence = function(id, vh_id, name, arr) {
    var path = [];
    var coor = arr.split(",");

    for (i = 0; i < coor.length; i++) {
        var ll = coor[i].split(" ");
        var lat = parseFloat(ll[0]);
        var lng = parseFloat(ll[1]);
        path.push(new google.maps.LatLng(lat, lng));
    }
    var p = new google.maps.Polygon({
        paths: path,
        editable: false,
        strokeColor: "#FF0000",
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: "#FF0000",
        fillOpacity: 0.35,
        map: map
    });
    var pObject = {
        id: id,
        vh_id: vh_id,
        name: name,
        state: '',
        polygon: p
    };

    polygons[id] = pObject;
};
find_geofence = function(id) {
    var p = null;
//    if (polygons) {
//        for (i in polygons) {
//            if (polygons[i].id === id) {
//                p = polygons[i];
//            } else {
//                polygons[i].polygon.setVisible(false);
//            }
//        }
//    }
    return p;
};
new_geofence = function() {


    if ((selectedMarker === null) || (selectedMarkerId <= 0)) {
        alert('Pilih Kendaraan/Nopol Lebih Dulu');
        return;
    }
    var imei = r.imei;
    var path = [];
    var center = map.getCenter(); //getPosition();
    var x1 = center.lng() - 0.1;
    var x2 = center.lng() + 0.1;
    var y1 = center.lat() - 0.1;
    var y2 = center.lat() + 0.1;
    path.push(new google.maps.LatLng(y1, x1));
    path.push(new google.maps.LatLng(y1, x2));
    path.push(new google.maps.LatLng(y2, x2));
    path.push(new google.maps.LatLng(y2, x1));


    var p = new google.maps.Polygon({
        paths: path,
        editable: true,
        draggable: true,
        strokeColor: "#FF0000",
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: "#FF0000",
        fillOpacity: 0.35
    });

    p.setMap(map);
    polygonEdit = {
        id: '',
        imei: imei,
        state: 'new',
        polygon: p,
        name: ''
    };
    //polygonEdit=pObject;
    //$("#btn_load").hide();
    $("#btn_new").hide();
    $("#btn_clear").hide();
    $("#btn_save").show();
    $("#btn_cancel").show();
    //$("#btn_update").hide();
};
play_audio = function() {
    var audioElement = document.createElement('audio');
    audioElement.setAttribute('src', 'http://www.uscis.gov/files/nativedocuments/Track%2093.mp3');
    audioElement.setAttribute('autoplay', 'autoplay');
    //audioElement.load()
    $.get();
    audioElement.addEventListener("load", function() {
        audioElement.play();
    }, true);

    $('.play').click(function() {
        audioElement.play();
    });


    $('.pause').click(function() {
        audioElement.pause();
    });

};
edit_geofence2 = function() {
    var row = $("#grid_geofence").datagrid('getSelected');
    console.log(row);
    if (row !== null) {
        edit_geofence(row.vh_id);
    }
};
edit_geofence = function(id)
{
    if (polygonEdit !== null) {
        alert(polygonEdit.state + ' State');
        return;
    }
    show_poi_control();
    polygonEdit = polygons[id];
    console.log(polygonEdit);
    if (polygonEdit !== null) {
        polygonEdit.polygon.setEditable(true);
        polygonEdit.polygon.setDraggable(true);
        polygonEdit.state = 'edit';
    }
//    dlgGeofence.dialog('open', {
//        buttons: [{
//                text: 'Save',
//                handler: function() {
//                }
//            }, {
//                text: 'Close',
//                handler: function() {
//                }
//            }]
//    });
};
add_geofence2 = function() {
    dlgGeofence.dialog('open');
    enable_measure_area_tool();
};
close_geofence_form = function() {
    dlgGeofence.dialog('close');
    close_measure_tool();
    reset_bg_toolbar_button();
};
save_geofence2 = function() {
    if (polygon !== null)
    {
        var path = polygon.getPath();//.getArray();
        var arr = path.getArray();
        var latlng = [];
        if (arr) {
            for (i in arr) {
                //console.log(arr[i].lat() + " " + arr[i].lng());
                latlng.push(arr[i].lat() + " " + arr[i].lng());
            }
        }
        formGeofence.form('load',
                {
                    path: latlng
                });
        $.messager.progress();
        formGeofence.form('submit', {
            url: 'php_script/save_geofence.php',
            onSubmit: function() {
                return true;//$(this).form('validate');
            },
            success: function(result) {
                $.messager.progress('close');
                var result = eval('(' + result + ')');
                if (result.errorCode > 0) {

                    $.messager.show({
                        title: 'Error',
                        msg: result.errorMsg
                    });

                } else {
                    $.messager.show({
                        title: 'Success',
                        msg: result.successMsg
                    });

                }
            }
        });


    }
};
save_geofence = function() {

    if (polygonEdit !== null)
    {
        var path = polygonEdit.polygon.getPath();//.getArray();
        //console.log(path.getArray());
        var arr = path.getArray();
        var latlng = [];
        if (arr) {
            for (i in arr) {
                //console.log(arr[i].lat() + " " + arr[i].lng());
                latlng.push(arr[i].lat() + " " + arr[i].lng());
            }
        }
        //var name =         
        polygonEdit.name = prompt("Ketik Nama Polygon", polygonEdit.name);
        console.log(polygonEdit);
        if (polygonEdit.name !== '')
        {
            //console.log(latlng);

            $.post('php_script/save_geofence.php', {id: polygonEdit.id, vh_id: polygonEdit.vh_id, name: polygonEdit.name, state: polygonEdit.state, polygon: latlng},
            function(result) {
                console.log(result);
                var vh_id = polygonEdit.vh_id;
                polygonEdit.polygon.setMap(null);
                polygonEdit = null;

                $("#btn_load").show();
                $("#btn_new").show();
                $("#btn_clear").show();
                $("#btn_save").hide();
                load_geofence(vh_id);

            }
            );
        }

    }
};
cancel_geofence = function() {
    polygon_state = 'none';
    if (polygonEdit.polygon !== null) {
        polygonEdit.polygon.setMap(null);
        polygonEdit = null;
    }
    //$("#btn_load").show();
    $("#btn_new").show();
    $("#btn_clear").show();
    $("#btn_save").hide();
    $("#btn_update").hide();
    $("#btn_cancel").hide();
};
clear_geofence = function() {
    if (polygonEdit !== null) {
        polygonEdit.polygon.setMap(null);
        polygonEdit = null;
    }
    if (polygons) {
        for (i in polygons) {
            polygons[i].polygon.setMap(null);
            polygons[i].polygon = null;
        }
    }
    polygons = [];

    $("#btn_load").show();
    $("#btn_new").show();
    $("#btn_clear").show();
    $("#btn_save").hide();
    $("#btn_update").hide();
    $("#btn_cancel").hide();
    $("#right").html("");
};
del_geofence = function(id) {
    $.post('php/del_polygon.php', {id: id},
    function(result) {
        load_geofence();
        alert(result);
    }
    );
};
default_polygon_button = function() {
    $("#btn_load").show();
    $("#btn_new").show();
    $("#btn_clear").show();
    $("#btn_save").hide();
    $("#btn_update").hide();
    $("#btn_cancel").hide();
    $("#cpolygon").html("");
};